#include "apue.h"
#include <fcntl.h>

const int BT_SIZE = 1;
const int KB_SIZE = 1 << 10;
const int MB_SIZE = 1 << 20;
const int GB_SIZE = 1 << 30;

/*
 * 解析输入的文件大小
 * @size    大小字符串1g, 1m, 1k, 1
 * @return  返回解析好的字节数
 *          失败直接退出程序
 */
int parser_size(const char *size)
{
    int i = 0, n = 0;
    char ch; // 遍历每一个字符
    while ((ch = size[i]))
    {
        if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'))
        {
            if(size[i + 1])
                err_quit("invalid input: %s", size);
            switch (ch)
            {
            case 'b':
            case 'B':
                return BT_SIZE * n;
            case 'k':
            case 'K':
                return KB_SIZE * n;
            case 'm':
            case 'M':
                return MB_SIZE * n;
            case 'g':
            case 'G':
                return GB_SIZE * n;
            default:
                err_quit("invalid input: %c", ch);
            }
        }
        else if ('0' <= ch && ch <= '9')
        {
            n = 10 * n + ch - '0';
        }
        else
        {
            err_quit("invalid input: %s", size);
        }
        i++;
    }
    return n;
}

int main(int argc, char **argv)
{
    if (argc < 3)
        err_quit("Usage: ./mkfile filename size");

    int sz = parser_size(argv[2]);

    int fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0755);
    if (-1 == fd)
        err_sys("create file error");

    if (-1 == lseek(fd, sz - 1, SEEK_SET))
        err_sys("create file error");

    if (1 != write(fd, " ", 1))
        err_sys("write data error");

    close(fd);
    return 0;
}
